﻿using Casamiel.API.Infrastructure;
using Casamiel.Common;
using Microsoft.AspNetCore.Mvc;
using NLog;
using System;
using System.Linq;

namespace Casamiel.API.Controllers
{

    /// <summary>
    /// 
    /// </summary>

    public class BaseController : ControllerBase
    {
        private readonly NLog.ILogger logger = LogManager.GetLogger("LoginInfo");

        /// <summary>
        /// 
        /// </summary>
        protected string Mobile {
            get {
                var token = Request.Headers["u-token"].ToString();
                return MemberHelper.GetMobile(token);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        protected string Referer => Request.Headers["Referer"].FirstOrDefault().ToLowerInvariant();

        /// <summary>
        /// logintype/source/datasource
        /// </summary>
        protected Tuple<int, int, int> LoginInfo {
            get {
                var source = 0;
                // 1、pc
                //2、ios app
                //3、android app
                //4、微信小程序
                //5、支付宝小程序
                var datasource = 1;
                var userAgent = Request.GetUserAgent();

                logger.Trace($"userAgent:{userAgent},Url:{Request.GetShortUri()},UserIP:{Request.GetUserIp()}");
                int loginType = 2;
                if (userAgent.Contains("CASAMIEL", StringComparison.OrdinalIgnoreCase)) {
                    if (userAgent.Contains("Android", StringComparison.OrdinalIgnoreCase)) {
                        loginType = 7;
                        datasource = 3;
                    } else {
                        loginType = 1;
                        datasource = 2;
                    }

                }
                if (userAgent.Contains("DONCO", StringComparison.OrdinalIgnoreCase)) {
                    loginType = 1;
                }
                if (loginType == 1) {
                    source = 1;

                }
                if (userAgent.Contains("MicroMessenger", StringComparison.OrdinalIgnoreCase)) {
                    loginType = 3;
                    source = 2;
                    datasource = 4;
                }

                if (userAgent.Contains("AlipayClient", StringComparison.OrdinalIgnoreCase)) {
                    loginType = 6;
                    source = 2;
                    datasource = 5;
                }
                return new Tuple<int, int, int>(loginType, source, datasource);
            }
        }
    }
}
